package com.android.jianboshi.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.KeyEvent;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.SPUtil;
import com.android.baselibrary.tool.XXPermisionUtil;
import com.android.baselibrary.util.DateUtil;
import com.android.baselibrary.view.MyBottomTabView;
import com.android.jianboshi.MyApplication;
import com.android.jianboshi.R;
import com.android.jianboshi.constants.SPConstants;
import com.android.jianboshi.dialog.BluetoothEnable_DialogFragment;
import com.android.jianboshi.dialog.PermisionNotice_DialogFragment;
import com.android.jianboshi.event.Event_Notification;
import com.android.jianboshi.manager.BluetoothHelper;
import com.android.jianboshi.ui.fragment.HomeMainFragment;
import com.android.jianboshi.ui.fragment.HomeMineFragment;
import com.android.jianboshi.ui.view.Tips_View;
import com.blankj.utilcode.util.ConvertUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity {


    public final static int HOME_INDEX_0 = 0;
    public final static int HOME_INDEX_1 = 1;
    public final static int HOME_INDEX_2 = 2;
    public final static int HOME_INDEX_3 = 3;
    public final static int HOME_INDEX_4 = 4;

    public static int curruntIndex;

    @BindView(R.id.mybottomtabview)
    MyBottomTabView mybottomtabview;
    @BindView(R.id.tips_view)
    Tips_View tips_view;

    Fragment currentFragment;
    BluetoothEnable_DialogFragment bluetoothEnableDialogFragment;  //蓝牙被关闭的弹窗

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        initTab();
        chooseFragment(HOME_INDEX_0);

    }

    //设置tab参数
    private void initTab() {
        mybottomtabview.setOnTabSelectCallBack(onBottomTabSelect);
        mybottomtabview.setTextColor(Color.parseColor("#555555"), getResources().getColor(com.android.baselibrary.R.color.mainColor));
        List<String> tab_name = new ArrayList<String>();   //文字
        tab_name.add(getString(R.string.tab_home));
        tab_name.add(getString(R.string.tab_mine));
        List<Integer> ico_normal = new ArrayList<>();       //默认图片
        ico_normal.add(R.drawable.ico_home_main_normal);
        ico_normal.add(R.drawable.ico_home_my_normal);
        List<Integer> ico_select = new ArrayList<>();
        ico_select.add(R.drawable.ico_home_main_select);       //选中图片
        ico_select.add(R.drawable.ico_home_my_select);
        mybottomtabview.setData(tab_name, ico_normal, ico_select, false, R.drawable.ico_home_bottom_center_);

    }

    @Override
    protected void initData() {
        List<String> arr = getNeedPermissions();
        boolean isGranted = XXPermissions.isGranted((Activity) mContext, arr);
        long PermisionDenyTime = SPUtil.getLoneValue(mContext, SPConstants.PermisionDenyTime, 0);
        Log.i("isGranted:" + isGranted+ "  PermisionDenyTime:" + PermisionDenyTime+ "  "+ new Date().getTime());
        if (!isGranted) {  //没有权限
            long delta = 60 * 60 * 24 * 2;
            if (new Date().getTime() - PermisionDenyTime < delta) {
                Log.i("PermisionDenyTime：" + PermisionDenyTime);
                return;
            }
            PermisionNotice_DialogFragment.showDialog((FragmentActivity) mContext, null).setCallback(new CommCallBack() {
                @Override
                public void onResult(Object obj) {
                    int result = (int) obj;
                    if (result == CommCallBack.Result_Success) {
                        //获取更新信息
                        XXPermisionUtil.requstPermision(mContext, new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                initBluTooth();
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
//                                OnPermissionCallback.super.onDenied(permissions, never);
                                //拒绝权限
                                Log.i("拒绝权限1");
                                SPUtil.putValue(mContext, SPConstants.PermisionDenyTime, new Date().getTime());
                            }
                        }, arr.toArray(new String[arr.size()]));
                    } else {
                        //拒绝权限
                        Log.i("拒绝权限2");
                        SPUtil.putValue(mContext, SPConstants.PermisionDenyTime, new Date().getTime());
                    }
                }
            });
        } else {
            initBluTooth();
        }
    }

    //初始化蓝牙
    BluetoothHelper bluetoothHelper;

    private void initBluTooth() {
        bluetoothHelper = new BluetoothHelper();
        if (bluetoothHelper.isOpen()) {
            Log.d("bt isOpen");
            bluetoothHelper.scan();
        } else {
            Log.d("bt not Open");
        }

        bluetoothHelper.setBroadCastCallback(new BluetoothHelper.BroadCastCallback() {
            @SuppressLint("MissingPermission")
            @Override
            public void onReceiverData(ScanResult result) {
                String deviceName = result.getDevice().getName();
                //先过滤自己设备
                if (TextUtils.isEmpty(deviceName)) return;
                if (!deviceName.startsWith("GYMSTR")) {
                    return;
                }
                //再过滤绑定设备
                String BindDeviceName = SPUtil.getStringValue(MyApplication.context, SPConstants.DeviceName, "");
                if (!TextUtils.isEmpty(BindDeviceName)) {
                    //判断是否绑定了过设备
                    if (!BindDeviceName.equals(deviceName)) {
                        return;
                    }
                }

                byte[] data = result.getScanRecord().getBytes();
                Event_Notification eventNotification = new Event_Notification();
                eventNotification.data = data;
                eventNotification.deviceName = deviceName;
                EventBus.getDefault().post(eventNotification);

                tips_view.setData(data);

                Log.i("deviceName:" + deviceName + " " + ConvertUtils.bytes2HexString(data));
            }
        });

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                bluetoothHelper.initData();
//            }
//        }, 5000);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                bluetoothHelper.initData();
//                Log.i("initData");
//            }
//        }, 6000);
    }


    private void showBluetoothDialog() {
        if (bluetoothEnableDialogFragment == null) {
            bluetoothEnableDialogFragment = (BluetoothEnable_DialogFragment) BluetoothEnable_DialogFragment.showDialog((FragmentActivity) mContext, null);
        }
    }

    private void closeBluetoothDialog() {
        if (bluetoothEnableDialogFragment != null) {
            bluetoothEnableDialogFragment.dismissWithAnim();
            bluetoothEnableDialogFragment = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bluetoothHelper.release();
        bluetoothHelper = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (bluetoothHelper != null) {
            if (bluetoothHelper.isOpen()) {
                bluetoothHelper.scan();
                closeBluetoothDialog();
            } else {
                showBluetoothDialog();
            }
        }
    }

    //切换Fragment
    private void chooseFragment(int index) {
        currentFragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(index));
        hideAllFrag();
        if (currentFragment == null) {
            switch (index) {
                case HOME_INDEX_0:
                    currentFragment = new HomeMainFragment();
                    break;
                case HOME_INDEX_1:
                    currentFragment = new HomeMineFragment();
                    break;
            }
            addFragment(currentFragment, index);
        } else {
            showFragment(currentFragment);
        }
        //切换刷新
        currentFragment.onResume();
        curruntIndex = index;
    }

    CommCallBack onBottomTabSelect = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            int index = (int) obj;
            if (index == mybottomtabview.centerIndex) {
                //点击加号回调
                CommToast.showToast(mContext, "点击加号");
//                Intent intent = new Intent(mContext, AddTaskActivity.class);
//                startActivity(intent);


            } else {
                chooseFragment(index);
                mybottomtabview.setSelect(index);
            }
        }
    };

    private void addFragment(Fragment currentFragment, int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.framelayout, currentFragment, index + "");
        ft.commitAllowingStateLoss();
    }

    private void hideAllFrag() {
        for (int i = 0; i < 5; i++) {
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(i));
            if (fragment != null) {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.hide(fragment);
                ft.commitAllowingStateLoss();
            }
        }
    }

    public void showFragment(Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (fragment.isDetached()) {
            ft.attach(fragment).show(fragment);
            ft.commitAllowingStateLoss();
        } else {
            ft.show(fragment);
            ft.commitAllowingStateLoss();
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                CommToast.showToast(mContext, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        currentFragment.onActivityResult(requestCode, resultCode, data);
    }

    //需要进行检测的权限
    private List<String> getNeedPermissions() {
        List<String> list = new ArrayList<>();
        //target sdk版本在29以上的需要精确定位权限才能搜索到蓝牙设备
        if (getApplicationInfo().targetSdkVersion >= 29) {
            list.add(Manifest.permission.ACCESS_FINE_LOCATION);
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        } else {
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        //Android 12需要
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            list.add(Manifest.permission.BLUETOOTH_SCAN);
            list.add(Manifest.permission.BLUETOOTH_CONNECT);
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        return list;
    }
}